//
//  TimeSensor.m
//  Pennyworth
//
//  Created by Chris Karr on 1/17/08.
//  Copyright 2008 Chris J. Karr. All rights reserved.
//

#import "TimeSensor.h"
#import "Context.h"
#import "SensorsController.h"

#define SENSOR_NAME @"Time of Day"

@implementation TimeSensor

@synthesize lastMinute;

- (void) awakeFromNib
{
	[[SensorsController sharedController] addSensor:SENSOR_NAME];

	minute = [[NSDateFormatter alloc] initWithDateFormat:@"%M" allowNaturalLanguage:NO];
	hour = [[NSDateFormatter alloc] initWithDateFormat:@"%H" allowNaturalLanguage:NO];
	weekday = [[NSDateFormatter alloc] initWithDateFormat:@"%A" allowNaturalLanguage:NO];
	
	self.lastMinute = nil;

	[[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update:) userInfo:nil repeats:YES] retain];
}

- (void) update:(NSTimer *) theTimer
{
	if (![[SensorsController sharedController] canFire:SENSOR_NAME])
	{
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
		[note setValue:@"Date-Time (Current Minute)" forKey:OBSERVATION_SENSOR];
		[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];

		note = [NSMutableDictionary dictionary];
		[note setValue:@"Date-Time (Current Hour)" forKey:OBSERVATION_SENSOR];
		[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];
		
		note = [NSMutableDictionary dictionary];
		[note setValue:@"Date-Time (Current Weekday)" forKey:OBSERVATION_SENSOR];
		[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];
		
		return;
	}		
	
	NSDate * now = [NSDate date];
	
	NSString * nowHour = [hour stringFromDate:now];
	NSString * nowWeekday = [weekday stringFromDate:now];
	NSString * nowMinute = [minute stringFromDate:now];

	if (![nowMinute isEqual:lastMinute])
	{
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
	
		[note setValue:@"Date-Time (Current Minute)" forKey:OBSERVATION_SENSOR];
		[note setValue:[NSNumber numberWithInteger:[nowMinute integerValue]] forKey:OBSERVATION_OBSERVATION];
		[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];

		[note setValue:@"Date-Time (Current Hour)" forKey:OBSERVATION_SENSOR];
		[note setValue:[NSNumber numberWithInteger:[nowHour integerValue]] forKey:OBSERVATION_OBSERVATION];
		[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];

		
		[note setValue:@"Date-Time (Current Weekday)" forKey:OBSERVATION_SENSOR];
		[note setValue:nowWeekday forKey:OBSERVATION_OBSERVATION];
		[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];
		
		self.lastMinute = nowMinute;
	}
}

@end
